import { createRouter, createWebHashHistory } from 'vue-router';
import type { RouteRecordRaw, Router } from 'vue-router';
import type { App } from "vue";
import { staticRouter, errorRouter, notFoundRouter } from './constant';
import { useGlobalStore } from '@/store/modules/global';
import { useMenuStore } from '@/store/modules/menu';

/**
* 创建路由表
*/
export const router = createRouter({
  history: createWebHashHistory(),
  routes: [...staticRouter, ...errorRouter] as RouteRecordRaw[],
  // 刷新时，滚动条位置还原
  scrollBehavior: () => ({ left: 0, top: 0 })
});

// 全局注册 router
export function setupRouter(app: App) {
  app.use(router);
}

// 根据获取的动态菜单栏 - 组装动态路由
export const initDynamicRouter = async () => {
  try {
    // 1. 提前扫描所有视图组件
    const viewsComponents = import.meta.glob('@/views/**/index.vue')

    const menuStore = useMenuStore()
    // 获取动态菜单栏 - 并保存在 store
    await menuStore.generateAuthMenuList()

    // 将动态菜单栏映射为动态路由表
    const dynamicRouter = getFlatArr(menuStore.getMenuList)
    dynamicRouter.forEach((item: any) => {

      // 2. 构造完整物理路径
      const componentPath = `/src/views${item.path}/index.vue`
      // 3. 安全获取组件
      const componentItem = viewsComponents[componentPath] || undefined

      if (!componentItem) {
        console.log('后台返回的路由,在前端未找到对应视图组件', componentPath)
        return
      }

      // 创建当前动态路由 - 加入到 layout 的子路由中
      const routeItem = {
        path: item.path,
        // component: () => import(`src/views${item.path}/index.vue`),
        component: componentItem,
        meta: { title: item.name }
      }
      router.addRoute('layout', routeItem)
    })

    // 最后放最终匹配路由
    router.addRoute(notFoundRouter)
  } catch (error) {
    router.replace('/login')
    return Promise.reject(error);
  }
}

export function getFlatArr(menulist: any[]) {
  return menulist.reduce((pre, current) => {
    let flatArr = [...pre, current]
    if (current.children)
      flatArr = [...flatArr, ...getFlatArr(current.children)]
    return flatArr
  }, [])
}
